/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 邓大帅
 * Date: 2023-02-22
 * Time: 14:12
 */
public class Sort2 {
    // 冒泡排序
    public static void bubbleSort(int[] array){
        for (int i = 0; i < array.length; i++) {
            boolean flag = true;
            for (int j = 0; j < array.length-1-i; j++) {
                if(array[j] > array[j+1]) {
                    swap(array, j, j+1);
                    flag = false;
                }
            }
            if(flag) {
                return;
            }
        }
    }
    private static void swap(int[] array, int n, int m) {
        int tmp = array[n];
        array[m] = array[n];
        array[n] = tmp;
    }

    // 快速排序
    public static void quickSort(int[] array) {
        quick(array, 0, array.length-1);
    }
    private static void quick(int[] array, int left, int right) {
        if(left >= right) {
            return;
        }
        //优化一
        if(right-left+1 == 4) {
            //此时序列已经趋于有序，这里可以用直接插入排序效率更快
        }
        //优化二:为了防止有特殊序列例如有序和逆序序列导致时间发杂度提高，
        //所以用三数取中法优化
        int k = midThree(array, left, right);
        swap(array, left, k);
        int i = index(array, left, right);
        index(array, left, i-1);
        index(array, i+1, right);
    }
    //挖坑法
    private static int index(int[] array, int left, int right) {
        int tmp = array[left];
        while (left < right) {
            while (left < right) {
                if(array[right] < tmp) {
                    array[left] = array[right];
                    break;
                }else {
                    right--;
                }
            }
            while (left < right) {
                if(array[left] > tmp) {
                    array[right] = array[left];
                    break;
                }else {
                    left++;
                }
            }
        }
        array[left] = tmp;
        return  left;
    }
    //三数取中法
    private static int midThree(int[] array, int left, int right) {
        int mid = (left + right) + 1;
        if(array[left] < array[right]) {
            if(array[mid] < array[left]) {
                return left;
            }else if(array[mid] > array[right]) {
                return right;
            }else  {
                return mid;
            }
        }else {
            if(array[mid] < array[right]) {
                return right;
            }else if(array[mid] > array[left]) {
                return left;
            }else {
                return mid;
            }
        }
    }
}
